package com.study.studyfive.mybatisPlus;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zhangwei
 * @version 1.0
 * @date 2023/12/2 13:38
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    RabbitTemplate rabbitTemplate;  // 使用RabbitTemplate,这提供了接收/发送等等方法


    @Autowired
    private UserMapper  userMapper;


    @RequestMapping("/test")
    @Transactional(rollbackFor = Exception.class)
    public  String   test() throws Exception {
        User user = new User();
        user.setName("张三1");
        user.setEmail("123@email.com");
        userMapper.insert(user);
        try {
            delete();
            int i = 1/0;
        }catch (Exception e) {
                throw new Exception(e.getMessage());
        }
        //发送消息到mq
      /*  try {
            sendDirectMsg();
        } catch (Exception e) {
            log.info("调用mq失败" + e.getMessage());
        }*/
        return "ok";
    }

    @RequestMapping("/delete")
   // @Transactional(rollbackFor = Exception.class)
    public String   delete() {
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("name", "张三");
        userMapper.delete(wrapper);
        return "ok";
    }






    public String sendDirectMsg() {
        String msgId = String.valueOf(UUID.randomUUID());
        String msmData = "test msg:" + Math.random();

        String createTime = DateUtil.now();
        Map<String, Object> map = new HashMap<>();
        map.put("msgId", msgId);
        map.put("msmData", msmData);
        map.put("createTime", createTime);
        String payload = JSON.toJSONString(map);
        log.info("打印的消息："+ payload);
        // 如果写的是默认交换机，可以不传交换机名称
        // rabbitTemplate.convertAndSend("TestDirectRouting", payload);
        // 将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", payload);
        return "ok";
    }

}
